//
//  UpdateImageViewController.m
//  Civacrm
//
//  Created by 王桂敏 on 2017/2/9.
//  Copyright © 2017年 王桂敏. All rights reserved.
//

#import "UpdateImageViewController.h"
#import "SchoolView.h"
#import "TZImagePickerController.h"

static NSString *inputViewPlaceholder = @"此时此刻，你又什么想法...";
@interface UpdateImageViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextViewDelegate,UITextFieldDelegate,TZImagePickerControllerDelegate>

@property (nonatomic,strong) UITextView *inputView;

@property (nonatomic,strong) UIButton *addButton;

@property (nonatomic,strong) SchoolView *schoolView;

@property (nonatomic, strong) UIImagePickerController *pickerC;

@property (nonatomic,strong) UIImageView *imageView;

@property (nonatomic,strong) UIImageView *buttonImageView;

@property (nonatomic,strong) TZImagePickerController *imagePickerController;

@end

@implementation UpdateImageViewController
{
    BOOL barFixed;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if (!barFixed) {
        barFixed = [InstrumentMIssingBar fixMissingBarWithVIewController:self];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initNavigation];
    [self initView];
    [self initNetWorkOfGetStudyRecord];
    
}
- (void)initNavigation{
    [self.rightButton setTitle:@"确定" forState:UIControlStateNormal];
    [self.leftButton setTitle:@"取消" forState:UIControlStateNormal];
    [self.leftButton setImage:nil forState:UIControlStateNormal];
}

- (void)initView{
    
    UIView *view = [UIView viewWithFrame:CGRectMake(0, 0, kScreenWidth, h(306)) bgColor:WhiteColor];
    [self.view addSubview:view];
    
    self.inputView = [[UITextView alloc] initWithFrame:CGRectMake(w(21), h(31), kScreenWidth - w(21) * 2, view.height - h(31) * 2 - h(120))];
    self.inputView.font = font(28);
    self.inputView.delegate = self;
    self.inputView.text = inputViewPlaceholder;
    self.inputView.textColor = ColorWithHexString(@"a0c0d2");
    [view addSubview:self.inputView];
    
    self.imageView = [UIImageView imageViewWithFrame:CGRectMake(w(20),view.height - h(31) - h(120), h(120), h(120)) image:nil];
    self.imageView.userInteractionEnabled = YES;
    [view addSubview:self.imageView];
    
    self.buttonImageView = [UIImageView imageViewWithFrame:self.imageView.frame image:@"btn_add_photo"];
    self.buttonImageView.userInteractionEnabled = YES;
    [view addSubview:self.buttonImageView];
    
    self.addButton = [UIButton buttonOfImageForNormalWithImage:nil frame:self.imageView.frame target:self action:@selector(handleAddButtonAction:)];
    self.addButton.imageView.frame = self.addButton.bounds;
    [view addSubview:self.addButton];
    
    self.schoolView = [[SchoolView alloc] initWithFrame:CGRectMake(0,getMaxY(view) + h(20), kScreenWidth, h(100))];
    self.schoolView.nameLabel.text = self.orgName;
    [self.view addSubview:self.schoolView];
    
}
- (UIImagePickerController *)pickerC{
    if (!_pickerC) {
        self.pickerC = [[UIImagePickerController alloc] init];
        _pickerC.delegate = self;
    }
    return _pickerC;
}

#pragma mark - buttonAction -
- (void)handleAddButtonAction:(UIButton *)sender{
    
    [self.view endEditing:YES];
    if (sender.isSelected) {
        self.imageView.image = nil;
        self.buttonImageView.image = Image(@"btn_add_photo");
        sender.selected = NO;
    } else {
        [self initImagePickerChooseView];
    }
    
}
- (void)handleRightButtonAction:(UIButton *)sender{
    if ([self.inputView.text isEqualToString:inputViewPlaceholder]) {
        [self showWarningWithStatus:@"任务内容不能为空"];
    } else if(!self.addButton.isSelected){
        [self showWarningWithStatus:@"图片内容不能为空"];
    } else {
        [self initNetWork];
    }
    
}
-(void)initImagePickerChooseView
{
    __weak typeof(self) weakSelf = self;
    
    UIAlertController *alertV = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    // 跳转到相册
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"从手机选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
                                {
                                    weakSelf.imagePickerController = [[TZImagePickerController alloc]initWithMaxImagesCount:1 delegate:self];
                                    [weakSelf.navigationController presentViewController:self.imagePickerController animated:YES completion:nil];
                                    
                                      
                                  }];
    
    [alertV addAction:photoAction];
    
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
        // 跳转到相机
        UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
                                       {
                                           
                                           weakSelf.pickerC.sourceType = UIImagePickerControllerSourceTypeCamera;
                                           [weakSelf presentViewController:weakSelf.pickerC animated:YES completion:^{}];
                                           
                                       }];
        [alertV addAction:cameraAction];
        
    }
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertV addAction:cancelAction];
    
    [self presentViewController:alertV animated:YES completion:nil];
    
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto
{
    self.addButton.selected = YES;
    self.buttonImageView.image = Image(@"btn_delet_img");
    self.imageView.image = photos[0];
    [self saveImage:photos[0] withName:@"SchoolDetailImageName"];
}

#pragma mark - image picker delegte -
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    if (image) {
        self.addButton.selected = YES;
        self.buttonImageView.image = Image(@"btn_delet_img");
        self.imageView.image = image;
        [self saveImage:image withName:@"SchoolDetailImageName"];
    } else {
        NSLog(@"图片获取失败");
    }
}

//  从内存中获取图片
- (UIImage *)getImageFromDocumentsWithName:(NSString *)name{
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:name];
    
    UIImage *savedImage = [[UIImage alloc] initWithContentsOfFile:fullPath];
    return savedImage;
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:^{}];
}
#pragma mark - 保存图片至沙盒
- (void)saveImage:(UIImage *)currentImage withName:(NSString *)imageName
{
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 0.5);
    // 获取沙盒目录
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
    // 将图片写入文件
    [imageData writeToFile:fullPath atomically:NO];
}


#pragma mark UITextViewDelegate
//  实现占位符的作用
- (void)textViewDidBeginEditing:(UITextView *)textView{
    
    [UIView animateWithDuration:0.25 animations:^{
        self.view.transform = CGAffineTransformMakeTranslation(0, 0);
    }];
    if ([textView.text isEqualToString:inputViewPlaceholder]) {
        textView.text = @"";
        textView.textColor = ColorWithHexString(@"4e778f");
    }
}
- (void)textViewDidEndEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:@""]) {
        textView.text = inputViewPlaceholder;
        textView.textColor = ColorWithHexString(@"a0c0d2");
    }
}
- (void)textViewDidChange:(UITextView *)textView
{
    NSRange textRange = [textView selectedRange];
    
    NSString *toBeString = textView.text;
    BOOL isEmoj = [self stringContainsEmoji:toBeString];
    
    toBeString = [self disable_emoji:toBeString];
    
    if (isEmoj) {
        
        textView.text = toBeString;
        [textView setSelectedRange:textRange];
    }
}
#pragma mark - touchesBegan -
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
    
}


#pragma mark - networkAndNetworkDelegate -
- (void)initNetWorkOfGetStudyRecord{
    
    self.params[@"uId"] = self.userID;
    self.params[@"subTaskId"] = self.subTaskId;
    
    [self showIndeterminate];
    [self.manager postWithURL:NET_GETSTUDYRECORD param:self.params delegate:self isEncrypt:NO type:NetWorkingType1];
    
}
- (void)initNetWork{
    
    [self showIndeterminate];
    self.params[@"uId"] = self.userID;
    self.params[@"taskId"] = self.model.taskModel.taskId;
    self.params[@"subTaskId"] = self.subTaskId;
    self.params[@"content"] = self.inputView.text;
    self.params[@"taskType"] = self.taskType;
    [self.manager postWithURL:NET_COMMITTASK imagePicName:@"baseCodes" image:[self getImageFromDocumentsWithName:@"SchoolDetailImageName"] param:self.params delegate:self isEncrypt:NO type:NetWorkingType0];
    
}

- (void)networkingHandleSuccess:(NetworkingHandle *)handle parameters:(NSDictionary *)parameters responseObject:(id)responseObject type:(NetWorkingType)type{
    [self hideHud];
    switch (type) {
        case NetWorkingType0:
        {
            
            if (self.block) {
                self.block();
            }
            [self.navigationController popViewControllerAnimated:YES];
        }
        break;
        case NetWorkingType1:
        {
            if (responseObject) {
                self.inputView.text = responseObject[@"studyContent"];
                if (![responseObject[@"studyImg"] isBlank]) {
                    self.addButton.selected = YES;
                    self.buttonImageView.image = Image(@"btn_delet_img");
                    [self.imageView sd_setImageWithURL:[NSURL URLWithString:responseObject[@"studyImg"]] placeholderImage:nil];
                    NSData *data = [NSData dataWithContentsOfURL:[NSURL  URLWithString:responseObject[@"studyImg"]]];
                    UIImage *image = [UIImage imageWithData:data];
                    [self saveImage:image withName:@"SchoolDetailImageName"];
                }
            }
            
            
            
        }
            break;
        
        default:
        break;
    }
    
}

- (void)networkingHandlefail:(NetworkingHandle *)handle type:(NetWorkingType)type{
    [self hideHud];
}

- (void)networkingHandleWarning:(NetworkingHandle *)handle responseObject:(id)responseObject type:(NetWorkingType)type{
    [self hideHud];
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
